package com.mohe.shanpao.netty.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class ChatClient {

	public static void main(String[] args) throws InterruptedException, IOException {
		EventLoopGroup group = new NioEventLoopGroup();
		
		try 
		{
			Bootstrap bootstrap  = new Bootstrap();
			
			bootstrap.group(group).channel(NioSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).handler(new ChannelInitializer<SocketChannel>(){

				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					 ChannelPipeline pipeline = ch.pipeline();
					 pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
					 pipeline.addLast("decoder", new StringDecoder());
				     pipeline.addLast("encoder", new StringEncoder());
				     pipeline.addLast("handler", new ChatClientHandler());
				}
				
			});
			
			ChannelFuture f = bootstrap.connect("localhost", 9988).sync();
			
//			f.addListener(new ChannelFutureListener() {
//				@Override
//				public void operationComplete(ChannelFuture future) throws Exception {
//					Channel channel = future.channel();
//					channel.writeAndFlush("aaaaaaaaaaaaa\r\n");
//				}
//			});
			
			Channel channel = f.channel();
			
			BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
			String msg = null;
			while(!"bye".equals(msg))
			{
				msg = in.readLine();
				channel.writeAndFlush(msg + "\r\n");
			}
			
		} finally {
			group.shutdownGracefully();
		}
	}

}
